/**
 * Created by Administrator on 2017/3/11.
 */
import React from 'react';
import { Radio ,Checkbox} from 'antd';
import './revise.css';
import {browserHistory} from "react-router";
const CheckboxGroup = Checkbox.Group;
//import { Input } from 'antd';
const RadioGroup = Radio.Group;
class Revise extends React.Component{
     constructor(props){
        super(props);
         this.state={
            difficulty:'',
            result:"",
            notes:"",
            contents:"",
             itemJson:"",
            problemType:"",
            list:""
        };
         this.onChange1=this.onChange1.bind(this);
         this.onChange=this.onChange.bind(this);
     }
  
    /**
     *
     * @param type 要修改的状态名称
     * @param e
     */
    onChange(type,e){
        this.setState({
            [type]: e.target.value
        });
    };
    onChange1(checkedValues){
        this.setState({result:checkedValues.toString()})
    };
    render(){
        return <form id="formobj">
        <div className="J_bj">
            <h2>编辑题目</h2>
            <div className="J_choose" style={{paddingBottom:'110px'}}>
                <div className="J_dir">
                    <span><em>*</em> 目录：</span>
                    <select name="" >
                        <option value="">一级目录</option>
                    </select>
                </div>
                <div className="J_type">
                    <span><em>*</em> 题型：</span>
                    <select name="" disabled style={{ cursor: 'not-allowed'}}>
                        <option value="">
                            {this.state.problemType===""?""
                                :this.state.problemType==='0'?"单选题"
                                    :this.state.problemType==='1'?"多选题"
                                        :"判断题"}
                            </option>
                    </select>
                    <div className="J_grade">
                        <span>难度等级：</span>
                        <RadioGroup onChange={this.onChange.bind(this,'difficulty')} value={this.state.difficulty}>
                            <Radio value={0}>易</Radio>
                            <Radio value={1}>中</Radio>
                            <Radio value={2}>难</Radio>
                        </RadioGroup>
                    </div>
                </div>
                <div className="J_topic">
                    <span><em>*</em> 题干：</span>
                    <div>
                        <textarea value={this.state.contents} onChange={this.onChange.bind(this,'contents')}></textarea>
                    </div>
                </div>
                <div className="J_option">
                    <span><em>*</em> 选项 <strong>单选题选项个数范围3到10，正确选项个数为1</strong></span>
                    {this.state.itemJson===""?"":JSON.parse(this.state.itemJson).map(function (result,index) {
                            return   <div key={index}>
                                        <span>{result.numberIndex}：</span>
                                        <div>
                                            <textarea  defaultValue={result.content}></textarea>
                                        </div>
                                        <div className="J_handle">
                                            <i className="J_up"></i>
                                            <i className="J_down"></i>
                                            <i className="J_delete"></i>
                                        </div>
                                        <strong className="J_hint"><span></span> 选项不能为空</strong>
                                 </div>
                        })}
                </div>
                <div className="J_add_option">
                    <em>+</em> <span> 添加一个选项</span>
                </div>
                <div className="J_key">
                    <span><em>*</em> 答案：</span>
                    {
                        this.state.problemType===""?""
                          :this.state.problemType==='1'?
                                <CheckboxGroup onChange={this.onChange1} options={this.state.list} defaultValue={this.state.result.split(',')}  />
                        :this.state.problemType==='0'?
                                    <RadioGroup onChange={this.onChange.bind(this, 'result')} value={this.state.result}>
                                    {this.state.list.map(function (result, index) {
                                        return <Radio key={index} value={result}>{result}</Radio>
                                    })}
                                </RadioGroup>
                                    : <RadioGroup onChange={this.onChange.bind(this, 'result')} value={this.state.result}>
                                        <Radio  value={'0'}>对</Radio>
                                        <Radio  value={'1'}>错</Radio>
                                    </RadioGroup>
                    }
                    <div className="J_hint"><span></span> 请选择正确答案</div>
                </div>
                <div className="J_analysis">
                    <span><em>*</em> 解析：</span>
                    <div>
                        <textarea value={this.state.notes} onChange={this.onChange.bind(this,'notes')}></textarea>
                    </div>
                </div>

            </div>
            <div className="J_func">
                <div>
                    <span className="J_preview">预览</span>
                    <span className="J_save">保存</span>
                </div>
            </div>
            <div className="J_model">
                <div>
                    <span>操作成功</span>
                </div>
            </div>
        </div>
        </form>
    }
    componentDidMount(){
        var _this=this;
        var letterIndex = "A,B,C,D,E,F,G,H,I,J".split(',');//x选项名称
        /**根据id查询数据，并修改状态**/
        $.ajax({
            type:"GET",
            data:{id:_this.props.params.id},
           // url:"http://192.168.2.9:8080/learn/s/resources/hProblems/form",
            url:"http://192.168.2.169:8080/s/resources/hProblems/form",
            success:function (result) {
                if(result.status==='OK'){
                    // console.log(result);
                    if(result.data.itemJson){
                        var arr=JSON.parse(result.data.itemJson);
                        var list=[];
                        for(var i=0;i<arr.length;i++){
                            list.push(arr[i].numberIndex);
                        }
                    }else{
                        result.data.itemJson="";
                    }
                    _this.setState({
                        list:list,
                        itemJson:result.data.itemJson,
                        difficulty: Number(result.data.difficulty),
                        result:result.data.result,
                        notes:result.data.notes,
                        contents:result.data.contents,
                        problemType:result.data.problemType,
                        id:result.data.id
                    });
                    if(result.data.problemType==='2'){//判断，如果是判断题就隐藏选项
                        $(".J_option").css('display','none');
                        $(".J_add_option").css('display','none');
                    }
                    Event();//绑定各种事件
                }else {
                  console.log('请求失败');
                }
            }
        });
        /**保存修改的数据**/
        $(".J_save").click(function () {
            var itemList = [];
            var _hint=true;
            $(".J_option div textarea").each(function (index) {
                if($.trim($(this).val())===""){
                    _hint=false;
                    $(this).parent().siblings('.J_hint').css('visibility','visible');
                    $(this).css('borderColor','#FF4141');
                }
                var _this = $(this);
                var item = {};
                item.itemIndex = index;//序号、排序
                item.numberIndex = letterIndex[index];//序号文本
                item.content = _this.val();//内容
                itemList.push(item);
            });
            /***如果是多选题，答案只有一个，则提示错误信息，不保存***/
            if(_this.state.problemType==='1'&&$(".J_key input:checked").length<2){
                $(".J_key .J_hint").css({'visibility':'visible'});
                _hint=false;
            }
            if(_this.state.problemType!=='2'){//判断选项是否相同
                $(".J_option div textarea").each(function (i) {
                    var _val=$(this).val();
                    if(i!==0&&_val!==''){
                        $(".J_option div textarea").slice(0,i).each(function (index) {
                            if($(this).val()===_val){
                                $(".J_option div textarea:eq("+i+")").parent()
                                    .siblings('.J_hint').css('visibility','visible');
                                $(".J_option div textarea:eq("+i+")").css('borderColor','#FF4141');
                                $(".J_option div textarea:eq("+i+")").parent()
                                    .siblings('.J_hint')
                                    .html('<span></span>与选项'+$(".J_option div textarea:eq("+index+")").parent().siblings('span').text().slice(0,1)+'重复')
                                _hint=false;
                            }
                        })
                    }
                  
                })
            }
            if(!_hint){
                return
            }
            if(_this.state.problemType==='1'){
                var result=[];
                $(".J_key input:checked").each(function (i) {
                    var _result=$(this).parent().siblings('span').text();
                    result.push(_result);
                })
                _this.state.result=result.toString();
            }
            _this.state.itemJson=JSON.stringify(itemList);//转化为json对象
            delete  _this.state.list;//删除属性
            console.log(_this.state);
            $.ajax({
                type:"POST",
                //url:"http://192.168.2.9:8080/learn/s/resources/hProblems/save",
                url:"http://192.168.2.169:8080/s/resources/hProblems/save",
                data: _this.state,
                success:function (data) {
                   if(data.status==="OK"){
                       browserHistory.push('/question');
                   }
                }
            })
        });
        function Event() {
            /**删除选项事件**/
            $(".J_option ").on('click','.J_delete',function () {
                var _length=$(".J_option div textarea").length
                // if(_length===3){
                //     return
                // }else {
                //     $(this).parent().parent().remove();
                //    bianhao()
                // }
                if (_length === 3 && _this.state.problemType === '0') {
                    return
                } else if (_length === 4 && _this.state.problemType === '1') {
                    return
                } else {
                    var _index = $(this).parent().parent().attr('value');
                    $(this).parent().parent().remove();
                    var _list = _this.state.list;
                    _list.splice(_index, 1);
                    for (var i = 0; i < _list.length; i++) {
                        _list[i] = letterIndex[i]
                    }
                    _this.setState({
                        list: _list
                    });
                    bianhao();

                }
            });
            /***向上移动**/
            $(".J_option").on('click','.J_up',function () {
                var nowValue=$(this).parent().siblings('div').children('textarea').val();
                var node=$(this).parent().parent().prev()[0].nodeName;
                var prevValue;
                if(node==='SPAN'){
                    prevValue= $(".J_option div textarea:last").val();
                    $(".J_option div textarea:last").val(nowValue);
                }else{
                    prevValue= $(this).parent().parent().prev().find('textarea').val();
                    $(this).parent().parent().prev().find('textarea').val(nowValue);
                }
                $(this).parent().siblings('div').children('textarea').val(prevValue);
            });
            /**向下移动**/
            $(".J_option ").on('click','.J_down',function () {
                var nowValue=$(this).parent().siblings('div').children('textarea').val();
                var next=$(this).parent().parent().next();
                var nextValue;
                if(next[0]){
                    nextValue= $(this).parent().parent().next().find('textarea').val();
                    $(this).parent().parent().next().find('textarea').val(nowValue);
                }else{
                    nextValue=$(".J_option div textarea:first").val();
                    $(".J_option div textarea:first").val(nowValue);
                }
                $(this).parent().siblings('div').children('textarea').val(nextValue);
            });
            /**添加选项**/
            $(".J_bj .J_add_option").click(function () {
                var _html=' <div >'+
                                 '<span></span>'+
                                '<div>'+
                                    '<textarea ></textarea>'+
                                    '</div>'+
                                    '<div class="J_handle">'+
                                    '<i class="J_up"></i>'+
                                    '<i class="J_down"></i>'+
                                    '<i class="J_delete"></i>'+
                                '</div>'+
                    '<strong class="J_hint"><span></span> 选项不能为空</strong>'+
                         '</div>';
                var _length=$(".J_option div textarea").length;
                if(_length===10){
                    return
                }else {
                    $(".J_option").append(_html);//添加到页面上
                    var _list=_this.state.list;
                    _list.push('1');
                    for(var i=0;i<_list.length;i++){
                        _list[i]=letterIndex[i]
                    }
                    _this.setState({list:_list});
                    bianhao();
                }
            });
            /**选项提示语**/
            $(".J_option").on('keyup','textarea',function () {
               if($.trim($(this).val())===""){
                   $(this).parent().siblings('.J_hint').css('visibility','visible')
                       .html('<span></span>选项不能为空');
                   $(this).css('borderColor','#FF4141');
               } else {
                   $(this).parent().siblings('.J_hint').css('visibility','hidden');
                   $(this).css('borderColor','#cccccc');
               }
            });
            /**答案提示语**/
            $(".J_key").on('change','input',function () {
               if(_this.state.problemType==='1'){//如果是多选题，答案只有一个，则提示错误信息
                   var _length=$('.J_key input:checked').length;
                   if(_length<2){
                       $('.J_key .J_hint').css('visibility','visible');
                       $(this).css('borderColor','#FF4141');
                   }else {
                       $('.J_key .J_hint').css('visibility','hidden');
                       $(this).css('borderColor','#cccccc');
                   }
               }
            });

            function bianhao() {
                $(".J_option div textarea").each(function (index) {//给每个选项编号A,B,C...
                    $(this).parent().siblings('span').text(letterIndex[index]+"：");
                });
            }
        }
    }
}
export default Revise;